package com.ruoyi.comparison.controller;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;

import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.comparison.domain.bo.TaskFileBo;
import com.ruoyi.comparison.domain.vo.TaskFileVo;
import com.ruoyi.comparison.domain.vo.TaskResultDetailVo;
import com.ruoyi.comparison.service.ITaskFileService;
import com.ruoyi.comparison.service.ITaskResultDetailService;
import lombok.RequiredArgsConstructor;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.apache.commons.io.IOUtils;
import org.bouncycastle.util.encoders.UTF8;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 投招文件信息
 *
 * @author ruoyi
 * @date 2023-11-05
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/file")
public class TaskFileController extends BaseController {

    private final ITaskFileService iTaskFileService;
    private final ITaskResultDetailService resultService;

    /**
     * 查询投招文件信息列表
     */
    @SaCheckPermission("system:oss:list")
    @GetMapping("/list")
    public TableDataInfo<TaskFileVo> list(TaskFileBo bo, PageQuery pageQuery) {
        return iTaskFileService.queryPageList(bo, pageQuery);
    }

    @SaCheckPermission("system:oss:list")
    @GetMapping("/preview")
    public void toPdfFile(Long id,HttpServletResponse response) {
        TaskResultDetailVo taskResultDetailVo = resultService.queryById(id);
        // 文件
        String newFileMix = taskResultDetailVo.getLeftBidUrl();
        try {
//            //通过SSH连接linux服务器上传文件
//            JSch jsch = new JSch();
//            Session session = jsch.getSession(SFTPClient.USER, SFTPClient.HOST, SFTPClient.PORT);
//            session.setPassword(SFTPClient.PASSWORD);
//            session.setConfig("StrictHostKeyChecking", "no");
//            session.connect();
//            ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");
//            channelSftp.connect();
//            InputStream in = channelSftp.get(newFileMix);
            // 使用response,将pdf文件以流的方式发送的前端浏览器上
            OutputStream outputStream = response.getOutputStream();
            // 读取文件
            InputStream in = Files.newInputStream(Paths.get(newFileMix));
            // copy流数据,i为字节数
            int i = IOUtils.copy(in, outputStream);
//            channelSftp.exit();
//            session.disconnect();
            in.close();
            outputStream.close();
            System.out.println("流已关闭,可预览,该文件字节大小："+i);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SaCheckPermission("system:oss:list")
    @GetMapping("/preview1")
    public void toPdfFile1(Long id,HttpServletResponse response) {
        // 执行的操作
        TaskResultDetailVo taskResultDetailVo = resultService.queryById(id);
        // 文件
        String newFileMix = taskResultDetailVo.getRightBidUrl();
        try {
//            //通过SSH连接linux服务器上传文件
//            JSch jsch = new JSch();
//            Session session = jsch.getSession(SFTPClient.USER, SFTPClient.HOST, SFTPClient.PORT);
//            session.setPassword(SFTPClient.PASSWORD);
//            session.setConfig("StrictHostKeyChecking", "no");
//            session.connect();
//            ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");
//            channelSftp.connect();
//            InputStream in = channelSftp.get(newFileMix);
            // 使用response,将pdf文件以流的方式发送的前端浏览器上
            ServletOutputStream outputStream = response.getOutputStream();
            // 读取文件
            InputStream in = Files.newInputStream(Paths.get(newFileMix));
            // copy流数据,i为字节数
            int i = IOUtils.copy(in, outputStream);
//            channelSftp.exit();
//            session.disconnect();
            in.close();
            outputStream.close();
            System.out.println("流已关闭,可预览,该文件字节大小："+i);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SaCheckPermission("system:oss:list")
    @GetMapping("/previewForm")
    public void previewForm(Long id,HttpServletResponse response) {
        // 执行的操作
        TaskResultDetailVo taskResultDetailVo = resultService.queryById(id);
        // 文件
        String newFileMix = taskResultDetailVo.getLeftFormUrl();
        if (ObjectUtil.isEmpty(newFileMix)){
            return;
        }
        try {
            // 使用response,将pdf文件以流的方式发送的前端浏览器上
            ServletOutputStream outputStream = response.getOutputStream();
            // 读取文件
            InputStream in = Files.newInputStream(Paths.get(newFileMix));
            // copy流数据,i为字节数
            int i = IOUtils.copy(in, outputStream);
            in.close();
            outputStream.close();
            System.out.println("流已关闭,可预览,该文件字节大小："+i);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SaCheckPermission("system:oss:list")
    @GetMapping("/previewForm1")
    public void previewForm1(Long id,HttpServletResponse response) {
        // 执行的操作
        TaskResultDetailVo taskResultDetailVo = resultService.queryById(id);
        // 文件
        String newFileMix = taskResultDetailVo.getRightFormUrl();
        try {
            // 使用response,将pdf文件以流的方式发送的前端浏览器上
            ServletOutputStream outputStream = response.getOutputStream();
            // 读取文件
            InputStream in = Files.newInputStream(Paths.get(newFileMix));
            // copy流数据,i为字节数
            int i = IOUtils.copy(in, outputStream);
            in.close();
            outputStream.close();
            System.out.println("流已关闭,可预览,该文件字节大小："+i);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出投招文件信息列表
     */
    @SaCheckPermission("system:oss:list")
    @Log(title = "投招文件信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(TaskFileBo bo, HttpServletResponse response) {
        List<TaskFileVo> list = iTaskFileService.queryList(bo);
        ExcelUtil.exportExcel(list, "投招文件信息", TaskFileVo.class, response);
    }
    /**
     * 预览文件接口
     */
    @SaCheckPermission("system:oss:list")
    @Log(title = "预览文件", businessType = BusinessType.EXPORT)
    @GetMapping("/downLoad")
    public void preview(HttpServletResponse response) {
        File file = new File("D:\\dev\\RuoYi-Vue-Plus\\fileStorage\\202311081327073570.docx"); // 文件的路径
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + "202311071352137630.doc");
            BufferedInputStream bis = new BufferedInputStream(fis);
            ServletOutputStream sos = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = bis.read(buffer)) != -1) {
                sos.write(buffer, 0, len);
            }
            sos.flush();
            sos.close();
            bis.close();
            fis.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 招标文件上传
     */
    @SaCheckPermission("system:oss:list")
    @PostMapping("/uploads1")
    @Transactional
    public R<List<String>> upload1(Long id, int type, @RequestParam("file") MultipartFile file) throws IOException {
        if (ObjectUtil.isNull(file)) {
            throw new ServiceException("上传文件不能为空");
        }
        String upload = iTaskFileService.upload1(id,file,type);
        if (ObjectUtil.isEmpty(upload)){
            throw new RuntimeException();
        }
        return R.ok(upload);
    }

    /**
     * 竞标文件上传
     */
    @SaCheckPermission("system:oss:list")
    @PostMapping("/uploads")
    @Transactional
    public R<List<String>> upload(Long id, int type, @RequestParam("file") List<MultipartFile> files) throws IOException{
        if (ObjectUtil.isNull(files)) {
            throw new ServiceException("上传文件不能为空");
        }
        List<String> stringList=new ArrayList<>();
        for (MultipartFile file : files) {
            String upload = iTaskFileService.upload(id,file,type);
            if (ObjectUtil.isEmpty(upload)){
                throw new RuntimeException();
            }
            stringList.add(upload);
        }
        return R.ok(stringList);
    }

    /**
     * 新增投招文件信息
     */
    @SaCheckPermission("system:oss:list")
    @GetMapping("/path/{id}")
    public R<String> path(@PathVariable("id") Long id) {
        return R.ok("/fileStorage/202311071352137630.doc");
    }
    /**
     * 获取投招文件信息详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("system:oss:list")
    @GetMapping("/{id}")
    public R<TaskFileVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(iTaskFileService.queryById(id));
    }

    /**
     * 新增投招文件信息
     */
    @SaCheckPermission("system:oss:list")
    @Log(title = "投招文件信息", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody TaskFileBo bo) {
        return toAjax(iTaskFileService.insertByBo(bo));
    }

}
